// src/pages/Dashboard/PersonalInfo.jsx

import React, { useState, useEffect } from 'react';
import { 
  Form, 
  Input, 
  Select, 
  Button, 
  Upload, 
} from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import styled from 'styled-components';
import { useDispatch, useSelector } from 'react-redux';
import { selectUserInfo, updateNurseInfo } from '../../../slices/userSlice'; // 假设添加了 updateNurseInfo
import { getDepartmentNames, getNurseNames } from '../../../request/wgqApi'; // 导入获取科室名称和护士名称的 API
import { message } from 'antd';

const Container = styled.div`
  padding: 24px;
  background: #fff;
  min-height: 100vh;
`;

const StyledForm = styled(Form)`
  max-width: 600px;
  
  .ant-form-item-label {
    width: 100px;
    text-align: right;
  }
  
  .ant-input[disabled] {
    color: rgba(0, 0, 0, 0.65);
    background-color: #f5f5f5;
  }
  
  .upload-area {
    width: 200px;
    height: 200px;
    border-radius: 8px;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
`;

const ButtonGroup = styled.div`
  margin-top: 24px;
  padding-left: 100px;
  
  .ant-btn {
    margin-right: 12px;
  }
`;

const PersonalInfo = () => {
  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const userInfo = useSelector(selectUserInfo);
  const loading = useSelector(state => state.user.loading);
  
  const [imageUrl, setImageUrl] = useState('/images/default-avatar.png'); // 使用绝对路径
  const [departments, setDepartments] = useState([]); // 存储科室列表
  const [nurseNames, setNurseNames] = useState([]); // 存储护士名称列表
  const [messageApi, contextHolder] = message.useMessage(); // 使用 message.useMessage

  useEffect(() => {
    // 获取科室名称和护士名称
    const fetchData = async () => {
      try {
        const [deptRes, nurseRes] = await Promise.all([
          getDepartmentNames(),
          getNurseNames()
        ]);
        if (deptRes.code === 1 && deptRes.data) {
          setDepartments(deptRes.data);
        } else {
          messageApi.error(deptRes.msg || '获取科室名称失败');
        }
        if (nurseRes.code === 1 && nurseRes.data) {
          setNurseNames(nurseRes.data);
        } else {
          messageApi.error(nurseRes.msg || '获取护士名称失败');
        }
      } catch (err) {
        console.error('获取科室或护士名称失败:', err);
        messageApi.error('获取科室或护士名称失败');
      }
    };
    
    fetchData();
  }, [messageApi]);
  
  useEffect(() => {
    if (userInfo) {
      form.setFieldsValue({
        account: userInfo.account,
        role: userInfo.purview,
        department: userInfo.department,
        name: userInfo.name,
        idCard: userInfo.idcard,
        phone: userInfo.phone,
      });
      // 构建完整的图片 URL，无需手动添加时间戳
      setImageUrl(userInfo.head ? `${userInfo.head}` : '/images/default-avatar.png');
    }
  }, [userInfo, form]);
  
  // 头像上传成功回调
  const handleUpload = async (info) => {
    if (info.file.status === 'done') {
      const { header, header_url } = info.file.response;
      if (header && header_url) {
        setImageUrl(`${header_url}`); // Redux store 已包含时间戳
        messageApi.success('头像上传成功');
        // 将头像文件名设置到表单中
        form.setFieldsValue({ head: header }); // 设置为 header（文件名）
      } else {
        messageApi.error('上传响应格式错误');
      }
    } else if (info.file.status === 'error') {
      messageApi.error('头像上传失败');
    }
  };
  
  // 上传组件配置
  const uploadProps = {
    name: 'file', // 对应后端的 'file' 字段
    action: 'http://localhost:21001/users/uploadheader', // 使用绝对路径，直接指向后端
    showUploadList: false,
    onChange: handleUpload,
    headers: {
      Authorization: `Bearer ${localStorage.getItem('t_k')}`, // 如果需要认证
    },
  };
  
  // 表单提交处理
  const handleSubmit = async (values) => {
    console.log('提交的表单数据：', values);
    const { role, department, name, idCard, phone, oldPassword, newPassword, head } = values;
    
    // 如果未上传新头像，则不传递 head 字段，保留现有头像
    const nurseInfo = {
      id: userInfo.id,
      name,
      idcard: idCard,
      phone,
      department,
      ...(head && { head }), // 仅在 head 存在时添加 head 字段
    };
    
    if (oldPassword && newPassword) {
      nurseInfo.oldpwd = oldPassword;
      nurseInfo.newpwd = newPassword;
    }
    
    try {
      await dispatch(updateNurseInfo(nurseInfo)).unwrap(); // 假设有 updateNurseInfo
      messageApi.success('个人信息修改成功');
      // Redux store 已经更新，头部组件应自动反映变化
      // 如果头部组件无法订阅 Redux store 的变化，则需要强制刷新页面
      window.location.reload();
    } catch (err) {
      console.error('修改个人信息失败:', err);
      messageApi.error('个人信息修改失败');
    }
  };
  
  return (
    <Container>
      {contextHolder}
      <StyledForm
        form={form}
        layout="horizontal"
        onFinish={handleSubmit}
      >
        {/* 护士账号 */}
        <Form.Item
          label="护士账号"
          name="account"
        >
          <Input disabled />
        </Form.Item>

        {/* 账号权限 */}
        <Form.Item
          label="账号权限"
          name="role"
        >
          <Select style={{ width: '100%' }} disabled> {/* 禁用选择权限 */}
            <Select.Option value="护士">护士</Select.Option>
            <Select.Option value="主任">主任</Select.Option>
          </Select>
        </Form.Item>

        {/* 旧密码 */}
        <Form.Item
          label="旧密码"
          name="oldPassword"
          rules={[
            {
              required: false,
              message: '请输入旧密码',
            },
          ]}
        >
          <Input.Password 
            placeholder="********（不修改密码则不用填写）" 
          />
        </Form.Item>

        {/* 新密码 */}
        <Form.Item
          label="新密码"
          name="newPassword"
          dependencies={['oldPassword']}
          rules={[
            ({ getFieldValue }) => ({
              validator(_, value) {
                const oldPassword = getFieldValue('oldPassword');
                if (!oldPassword && value) {
                  return Promise.reject(new Error('必须先输入旧密码'));
                }
                return Promise.resolve();
              },
            }),
          ]}
        >
          <Input.Password 
            placeholder="********（不修改密码则不用填写）" 
          />
        </Form.Item>

        {/* 姓名 */}
        <Form.Item
          label="姓名"
          name="name"
          rules={[{ required: true, message: '请输入姓名' }]}
        >
          <Input />
        </Form.Item>

        {/* 身份证号 */}
        <Form.Item
          label="身份证号"
          name="idCard"
          rules={[{ required: true, message: '请输入身份证号' }]}
        >
          <Input />
        </Form.Item>

        {/* 手机号 */}
        <Form.Item
          label="手机号"
          name="phone"
          rules={[{ required: true, message: '请输入手机号' }]}
        >
          <Input />
        </Form.Item>

        {/* 科室更改 */}
        <Form.Item
          label="科室更改"
          name="department"
          rules={[{ required: true, message: '请选择科室' }]}
        >
          <Select style={{ width: '100%' }}>
            {departments.map((dept, index) => (
              <Select.Option key={index} value={dept.name}>
                {dept.name}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>

        {/* 头像上传 */}
        <Form.Item
          label="更改照片"
          name="head" // 对应后端的 'head' 字段
        >
          <div className="upload-area">
            <Upload {...uploadProps}>
              {imageUrl ? (
                <img src={imageUrl} alt="头像" />
              ) : (
                <Button icon={<UploadOutlined />}>点击上传</Button>
              )}
            </Upload>
          </div>
        </Form.Item>

        {/* 按钮组 */}
        <ButtonGroup>
          <Button type="primary" htmlType="submit" loading={loading}>
            确认修改
          </Button>
          <Button onClick={() => window.history.back()}>
            返回上一级
          </Button>
        </ButtonGroup>
      </StyledForm>
    </Container>
  );
};

// 全局样式
const GlobalStyle = styled.div`
  .ant-input, .ant-select-selector {
    border-radius: 4px !important;
  }

  .ant-btn {
    border-radius: 4px;
    height: 32px;
    padding: 0 16px;
  }
  
  .ant-form-item {
    margin-bottom: 24px;
  }

  .upload-area {
    border: 1px dashed #d9d9d9;
    padding: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .upload-area img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
`;

export default () => (
  <GlobalStyle>
    <PersonalInfo />
  </GlobalStyle>
);